package com.larsgard.gedviewer.server.services;

import java.util.logging.Logger;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.larsgard.gedviewer.client.service.GedUserService;
import com.larsgard.gedviewer.shared.ajax.IsLoggedInResponse;
import com.larsgard.gedviewer.shared.ajax.LoggedInRequest;

public class UserServiceImpl extends RemoteServiceServlet implements GedUserService {

    private static Logger log = Logger.getLogger(UserServiceImpl.class.getName());
    private static final long serialVersionUID = 6845002429638795144L;

    @Override
    public IsLoggedInResponse isLoggedIn(LoggedInRequest request) {
	log.info("url is " + request.getUrl());
	IsLoggedInResponse result = new IsLoggedInResponse();
	UserService userService = UserServiceFactory.getUserService();
	if (userService.isUserLoggedIn()) {
	    if (isAllowed(userService.getCurrentUser())) {
		result.setLoggedIn(true);
		result.setLoginName(userService.getCurrentUser().getEmail());
		result.setLoginUrl(userService.createLogoutURL(request.getUrl()));
	    } else {
		result.setLoggedIn(false);
		result.setLoginUrl(userService.createLoginURL(request.getUrl()));
	    }
	} else {
	    result.setLoggedIn(false);
	    result.setLoginUrl(userService.createLoginURL(request.getUrl()));
	}

	return result;
    }

    /**
     * Used for limiting access in testing periods
     */
    private boolean isAllowed(User currentUser) {
	// String mail = currentUser.getEmail();
	// boolean result = false;
	// result |= mail.equalsIgnoreCase("nilsmagnus@gmail.com");
	// result |= mail.equalsIgnoreCase("k.larsgaard@gmail.com");
	// result |= mail.equalsIgnoreCase("knutinge.larsgard@gmail.com");
	// result |= mail.equalsIgnoreCase("odin.hole.standal@gmail.com");
	// return result;
	return true;
    }

}
